﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;

namespace MS.InformationManagement.Support
{
    public static class TermStoreHelper
    {

        /// <summary>
        /// Get a termset 
        /// </summary>
        /// <param name="taxonomyGroupName">Group name</param>
        /// <param name="taxonomyTermSet">Termset name</param>
        /// <returns>Termset object</returns>
        public static TermSet GetTermSetByName(string taxonomyGroupName, string taxonomyTermSet)
        {
            var taxonomyGroup = GetTaxonomyGroupByName(taxonomyGroupName);
            if (taxonomyGroup == null) throw new Exception("Taxonomy group:" + taxonomyGroupName + " does not exits");
            return taxonomyGroup.TermSets.Where(c => string.Compare(c.Name, taxonomyTermSet, true) == 0).FirstOrDefault();
        }

        /// <summary>
        /// Get a taxonomy group by its name
        /// </summary>
        /// <param name="GroupName">Taxonomy group name</param>
        /// <returns></returns>
        public static Group GetTaxonomyGroupByName(string GroupName)
        {
            var site = SPContext.Current.Site;
            var session = new TaxonomySession(site);
            return session.TermStores[ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.METADATA_SERVICE_NAME]].Groups.Where(c => string.Compare(c.Name, GroupName, true) == 0).FirstOrDefault();
        }

        /// <summary>
        /// Get a taxonomyfieldvalue from managed metadata service
        /// </summary>
        /// <param name="taxonomyGroupName">Group Name</param>
        /// <param name="taxonomyTermSet">Termset Name</param>
        /// <param name="taxonomyTerm">Term to find</param>
        /// <returns>Taxonomy field value</returns>
        public static TaxonomyFieldValue GetTaxonomyFieldByTerm(string taxonomyGroupName, string taxonomyTermSet, string taxonomyTerm)
        {

            var taxonomyTermS = GetTermSetByName(taxonomyGroupName, taxonomyTermSet);
            if (taxonomyTermS == null) throw new Exception("Termset:" + taxonomyTermSet + " does not exists");
            var term = taxonomyTermS.Terms.Where(c => string.Compare(c.Name, taxonomyTerm, true) == 0).FirstOrDefault();
            if (term == null) throw new Exception("Term:" + taxonomyTerm + " does not exist");
            TaxonomyFieldValue val = new TaxonomyFieldValue(string.Empty);
            val.PopulateFromLabelGuidPair(taxonomyTerm + "|" + term.Id);
            val.WssId = -1;

            return val;

        }

        public static TaxonomyFieldValue GetTaxonomyFieldByTerm(string taxonomyGroupName, string taxonomyTermSet, string taxonomyTerm, bool searchRecursively)
        {
            if (searchRecursively)
            {
                var taxonomyTermS = GetTermSetByName(taxonomyGroupName, taxonomyTermSet);
                if (taxonomyTermSet == null) throw new Exception("Termset:" + taxonomyTermSet + " does not exists");               
                TaxonomyFieldValue taxonomyField = null;
                foreach (Term currentTerm in taxonomyTermS.Terms)
                {
                    SearchTaxonomyField(currentTerm, taxonomyTerm, ref taxonomyField);
                }

                return taxonomyField;
            }
            else { return GetTaxonomyFieldByTerm(taxonomyGroupName, taxonomyTermSet, taxonomyTerm); }
        }

        private static void SearchTaxonomyField(Term termset, string taxonomyTerm, ref TaxonomyFieldValue taxonomyField)
        {
            if (taxonomyField != null) { return; }
            else
                if (termset.Terms.Count > 0)
                {
                    foreach (Term currentTerm in termset.Terms)
                    {
                        SearchTaxonomyField(currentTerm, taxonomyTerm, ref taxonomyField);
                    }
                }
                else
                {
                    if (termset.Name.Equals(taxonomyTerm))
                    {
                        taxonomyField = new TaxonomyFieldValue(string.Empty);
                        taxonomyField.PopulateFromLabelGuidPair(taxonomyTerm + "|" + termset.Id);
                    }
                }
        }

        public static TaxonomyFieldValue GetTaxomyFieldByTerm(Term taxonomyTerm)
        {
            TaxonomyFieldValue val = new TaxonomyFieldValue(string.Empty);
            val.PopulateFromLabelGuidPair(taxonomyTerm.Labels[0] + "|" + taxonomyTerm.Id);
            val.WssId = -1;
            return val;
        }

        public static TermCollection GetBrotherTerms(TaxonomyFieldValue taxonomyValue, string group, string rootTermSet)
        {
            TermSet countryTerm = TermStoreHelper.GetTermSetByName(group, rootTermSet);
            Term selectedCity = countryTerm.GetTerm(new Guid(taxonomyValue.TermGuid));
            Term SelectedState = selectedCity.Parent;
            return SelectedState.Terms;
        }

        public static Term GetParentTerm(TaxonomyFieldValue taxonomyValue, string group, string rootTermSet)
        {
            TermSet countryTerm = TermStoreHelper.GetTermSetByName(group, rootTermSet);
            Term selectedCity = countryTerm.GetTerm(new Guid(taxonomyValue.TermGuid));
            return selectedCity.Parent;
        }

        public static Term GetTermByTaxonomyValue(TaxonomyFieldValue taxonomyValue, string group, string rootTermSet)
        {
            TermSet countryTerm = TermStoreHelper.GetTermSetByName(group, rootTermSet);
            Term selectedCity = countryTerm.GetTerm(new Guid(taxonomyValue.TermGuid));
            return selectedCity;
        }

    }
}
